package org.obs.service.impl;

import org.acegisecurity.Authentication;
import org.acegisecurity.context.SecurityContextHolder;
import org.acegisecurity.ui.logout.LogoutHandler;
import org.apache.commons.lang.StringUtils;
import org.obs.aop.RequestInterceptor;
import org.obs.service.LoginService;

public class LoginServiceImpl implements LoginService {
	
	private LogoutHandler logoutHandler;

	public LogoutHandler getLogoutHandler() {
		return logoutHandler;
	}

	public void setLogoutHandler(LogoutHandler logoutHandler) {
		this.logoutHandler = logoutHandler;
	}

	public boolean isLogged() {
		boolean isAuthenticated = SecurityContextHolder.getContext().getAuthentication().isAuthenticated();		
		String name = SecurityContextHolder.getContext().getAuthentication().getName();
		boolean isAnonymous = "anonymousUser".equalsIgnoreCase(name) || StringUtils.isBlank(name);
		return isAuthenticated && !isAnonymous;
	}

	public void logout() {
		if (isLogged()) {
			Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); 
			logoutHandler.logout(RequestInterceptor.getRequest(), RequestInterceptor.getResponse(), authentication);
			SecurityContextHolder.getContext().setAuthentication(null);
		}
	}

	public void login() {
		throw new UnsupportedOperationException("Login must not explicity call");
	}

	public String getLoggedUserName() {
		String name = SecurityContextHolder.getContext().getAuthentication().getName();
		return name;
	}

}
